package com.bms.admin.config;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.apache.poi.util.IOUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import cn.afterturn.easypoi.cache.ImageCache;
import cn.afterturn.easypoi.cache.manager.POICacheManager;

@Component
public class ExcelListener implements ApplicationListener<ApplicationReadyEvent> {

	@Override
	public void onApplicationEvent(ApplicationReadyEvent event) {
		LoadingCache<String, byte[]> loadingCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.DAYS)
        .maximumSize(2000).build(new CacheLoader<String, byte[]>() {
            @Override
            public byte[] load(String imagePath) throws Exception {
                InputStream is = POICacheManager.getFile(imagePath);
                BufferedImage bufferImg = ImageIO.read(is);
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                try {
                    ImageIO.write(bufferImg,
                        imagePath.substring(imagePath.lastIndexOf(".") + 1, imagePath.length()),
                        byteArrayOut);
                    return byteArrayOut.toByteArray();
                } finally {
                    IOUtils.closeQuietly(is);
                    IOUtils.closeQuietly(byteArrayOut);
                }
            }
        });
		ImageCache.setLoadingCache(loadingCache);
		POICacheManager.setFileLoder(new EasypoiFileLoader());
	}
	

}
